package com.nc.shop.service.service.impl;

import com.nc.shop.service.dao.CarDao;
import com.nc.shop.service.dao.OrderDao;
import com.nc.shop.service.dao.ShopDao;
import com.nc.shop.service.model.entity.CarEntity;
import com.nc.shop.service.model.entity.OrderEntity;
import com.nc.shop.service.model.entity.RepertoryEntity;
import com.nc.shop.service.model.entity.ShopEntity;
import com.nc.shop.service.service.OrderService;
import com.nc.shop.service.service.RedisService;
import com.nc.shop.service.service.RepertoryService;
import com.plug.result.RetResponse;
import com.plug.result.RetResult;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    CarDao carDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    RedisService redisService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    ShopDao shopDao;
    @Autowired
    RepertoryService repertoryService;

    @Override
    @Transactional
    public RetResult addOrder(List<String> ids) {
        List<CarEntity> cars = carDao.findByIdIn(ids);
        OrderEntity order = new OrderEntity();
        order.setMoney(cars.stream().map(CarEntity::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add));
        JSONObject user = JSONObject.fromObject(redisService.get(request.getHeader("token")));
        order.setName(user.getString("nickName"));
        order.setUserId(user.getString("id"));
        order.setNumber(cars.stream().mapToInt(CarEntity::getNumber).sum());
        order.setType(0);
        order.setStatus(0);
        OrderEntity finalOrder = orderDao.save(order);
        cars.forEach(item -> {
            OrderEntity orderItem = new OrderEntity();
            orderItem.setMoney(item.getMoney());
            orderItem.setName(user.getString("nickName"));
            orderItem.setNumber(item.getNumber());
            orderItem.setParentId(finalOrder.getId());
            orderItem.setType(1);
            orderItem.setStatus(0);
            orderItem.setUserId(user.getString("id"));
            orderItem.setShopId(item.getShopId());
            orderDao.save(orderItem);
            Optional<ShopEntity> shop = shopDao.findById(item.getShopId());
            RepertoryEntity repertoryEntity = new RepertoryEntity();
            repertoryEntity.setShopEntity(shop.get());
            repertoryEntity.setNumber(item.getNumber());
            repertoryEntity.setNote(user.getString("id") + "的订单");
            repertoryService.out(repertoryEntity);
        });
        return RetResponse.makeOKRsp();
    }
}
